from flask import Flask, request, jsonify
from flask_cors import CORS
from file import Documentsplit
from openai import OpenAI
import os
import uuid

app = Flask(__name__)
CORS(app)
app.secret_key = 'jdwiqjdjjijioiooj'

api_key = 'sk-bphodwvjqrzayelwjmbfvgmgwlzjbhpexxmvazkdemrlzyst'
api_url = 'https://api.siliconflow.cn/v1'
model = 'Qwen/Qwen3-235B-A22B'

client = OpenAI(api_key=api_key, base_url=api_url)

# 创建全局变量存储处理后的对象
processed_documents = {}



@app.route('/generate', methods=['POST'])
def generate_content():
        file_path='./依赖安装.txt'
        ds = Documentsplit(file_path).load_file()
        data = request.json
        session_id = data.get('session_id')  # 获取会话ID
        user_input = data.get('input', '')

        if not user_input:
            return jsonify({"status": "error", "message": "Input content is required"}), 400

        docs = ds.similarity_search(user_input)
        context= "\n".join([doc.page_content for doc in docs])



        messages = [
            {'role': 'system', 'content': '你是一个基于知识库的AI助手，请根据以下上下文回答问题。可以简写，争取5秒内答完'},
            {'role': 'user', 'content': f"上下文:\n{context}\n\n问题:{user_input}"}
        ]

        response = client.chat.completions.create(
            model=model,
            messages=messages,
            stream=True
        )

        generated_text = ""
        for chunk in response:
            if chunk.choices and chunk.choices[0].delta.content:
                generated_text += chunk.choices[0].delta.content

        return jsonify({
            "status": "success",
            "input": user_input,
            "generated_content": generated_text,
            "context_length": len(context)  # 可选：返回上下文长度用于调试
        })


if __name__ == '__main__':
    app.run(port=5000)